package com.sun.demo;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.sun.Beens.Feedback;
import com.sun.Beens.Installation;
import com.sun.BmobDemo.UserAccount;
import com.sun.BmobDemo.been;

import java.util.List;
import java.util.jar.Attributes;

import cn.bmob.push.BmobPush;
import cn.bmob.sms.BmobSMS;
import cn.bmob.sms.exception.BmobException;
import cn.bmob.sms.listener.RequestSMSCodeListener;
import cn.bmob.sms.listener.VerifySMSCodeListener;
import cn.bmob.v3.BmobInstallation;
import cn.bmob.v3.BmobPushManager;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.DeleteListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

/*
*本类基于BMOB的各种方法，组合在一个类中
* Bmob_Push_V0.6beta_20150408.jar消息推送jar包
* BmobSDK_V3.4.5_1111  bmob SDK jar包
* BmobSMS_V1.0.1_20150710  短信功能jar包
*
* 需要把JAe包复制到libs中，并设置为依赖
* AndroidManifest中注册权限
*
*   <!-- 网络权限 -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <!-- Push SDK权限 end -->
    <!-- 允许网络连接以及网络状态改变 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <!-- 文件存储 -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
*
*
*         <service
            android:name="cn.bmob.push.lib.service.PushService"
            android:exported="true"
            android:label="PushService"
            android:process=":bmobpush" >
            <intent-filter>
                <action android:name="cn.bmob.push.lib.service.PushService" />
            </intent-filter>
        </service>
        <receiver android:name="cn.bmob.push.PushReceiver" android:process=":bmobpush">
            <intent-filter android:priority="2147483647" > <!-- 优先级加最高 -->
                <!-- 系统启动完成后会调用 -->
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <!-- 解锁完成后会调用 -->
                <action android:name="android.intent.action.USER_PRESENT" />
                <!-- 监听网络变化 -->
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>
        <receiver android:name="com.sun.demo.MessageReceiver" >
            <intent-filter>
                <action android:name="cn.bmob.push.action.MESSAGE" />
            </intent-filter>
        </receiver>
*
*
* ++++++首先需要初始化initBmob(Context context,String AppID)
*
*1.发送短信验证码 sendSMSCheckedNum(String phoneNum,String s)
* S为短信模板sms
*
* 2.验证短信checkSmsNum(String phoneNum,String checkNum)
*
* 3.注册调用addUserAccount( final UserAccount account)
* 如需要跳转可以重写intentTo()
*
* 4.向数据库添加数据addData(been acc)
* 如需要跳转可以重写intentTo()
*
* 5.删除单一用户调用delByName(String userName)
*
* 4.更新用户信息updataUserAccount(final UserAccount account)
*
* 6.查询单条数据调用quertByName(String userName)
* 之后重写returnUser(UserAccount account)方法获取UserAccount对象数据
*
* 7.查询所有数据调用queryAll()
* 之后重写returnUser(List<UserAccount> account)获取UserAccount对象集合数据
*
*8.
*
**/
public abstract class Bmob extends Activity{

    private Boolean flag;//短信验证成功标志
    Context context;
    private BmobPushManager<BmobInstallation> bmobPush;

    //初始化
    public  void initBmob(Context context,String AppID){
        //bmob SDK初始化
        this.context = context;
        cn.bmob.v3.Bmob.initialize(context, AppID);
        //短信初始化
        BmobSMS.initialize(context, AppID);
        //推送初始化
        BmobPush.startWork(context, AppID);
        BmobInstallation.getCurrentInstallation(this).save();
        bmobPush = new BmobPushManager<BmobInstallation>(context);
    }
    //----------------------------短信验证码功能开始--------------------------------------//
    //发送短信验证码  需要传入手机号和短信模板名字

    /**
     * @param phoneNum 电话号码
     * @param s        短信模板（sms）
     */
    public void sendSMSCheckedNum(String phoneNum,String s){
        BmobSMS.requestSMSCode(context, phoneNum, s, new RequestSMSCodeListener() {
            @Override
            public void done(Integer integer, BmobException e) {
                if (e == null) {
                    Toast.makeText(context, "验证码发送成功！", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //短信验证码验证，返回Boolean类型
    public  void checkSmsNum(String phoneNum,String checkNum){
        flag = false;
        Log.i("1",phoneNum+"+"+checkNum);
        BmobSMS.verifySmsCode(context, phoneNum, checkNum, new VerifySMSCodeListener() {
            @Override
            public void done(BmobException e) {
                //验证码验证成功
                if (e == null) {
                    Toast.makeText(context, "验证码正确！", Toast.LENGTH_SHORT).show();
//                    flag = true;
                } else {
                    Log.i("1",e.toString());
                    Toast.makeText(context, "验证码不正确！", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        });
//        return flag;
    }

    //----------------------------短信验证码功能结束--------------------------------------//
    //----------------------------网络数据操作功能开始--------------------------------------//
    /**
     *添加数据
     * 注册（进行重名检测，不重名就添加，重名就返回用户已存在）
     * 需要重写intentTo()方法进行跳转
     * @param account
     */
    public  void  addUserAccount( final UserAccount account) {
        //查询是否重名

        BmobQuery<UserAccount> query = new BmobQuery<UserAccount>();
        query.addWhereEqualTo("name", account.getName());
        query.findObjects(context, new FindListener<UserAccount>() {
            @Override
            public void onSuccess(List<UserAccount> list) {
                if (list.size() == 0) {
                    addData(account);
                } else {
                    Toast.makeText(context, "用户名已存在！", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            @Override
            public void onError(int i, String s) {
                Toast.makeText(context, "注册失败！原因：" + s.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    //不重名，添加到数据库,并跳转到登录界面
    //向数据库添加数据
    public void addData(been acc){
    //向数据库添加数据
        BmobQuery<been> query = new BmobQuery<been>();
        acc.save(context, new SaveListener() {
            @Override
            public void onSuccess() {
                Toast.makeText(context, "添加成功！", Toast.LENGTH_SHORT).show();
                intentTo();
            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(context, "添加失败！原因：" + s.toString(), Toast.LENGTH_SHORT).show();
            }
        });


    }
    private void addData(UserAccount acc){
        BmobQuery<UserAccount> query = new BmobQuery<UserAccount>();
        acc.save(context, new SaveListener() {
            @Override
            public void onSuccess() {
                Toast.makeText(context, "注册成功！", Toast.LENGTH_SHORT).show();
                intentTo();
            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(context, "注册失败！原因：" + s.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    //跳转方法
    public   void intentTo(){};
    /**
     * 删除一条数据
     * @param userName
     */
    public void delByName(String userName) {
        //查询用户名为userName

        BmobQuery<UserAccount> query = new BmobQuery<UserAccount>();
        query.addWhereEqualTo("name", userName);
        query.findObjects(context, new FindListener<UserAccount>() {
            @Override
            public void onSuccess(List<UserAccount> list) {
                if (list.size() != 0) {
                    UserAccount account = new UserAccount();
                    account.setObjectId(list.get(0).getObjectId());
                    del(account);
                } else {
                    Toast.makeText(context, "数据不存在,无需删除！", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            @Override
            public void onError(int i, String s) {
                Toast.makeText(context, "删除失败！" + s, Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void del(UserAccount user){
        //根据查询结果执行删除
        user.delete(context, new DeleteListener() {
            @Override
            public void onSuccess() {
                Toast.makeText(context, "删除成功！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(context, "删除失败！" + s, Toast.LENGTH_SHORT).show();
            }
        });

    }
    /**
     * 数据更新
     * @param account
     */
    public  void  updataUserAccount(final UserAccount account) {
        //更新：查询是否重名

        BmobQuery<UserAccount> query = new BmobQuery<UserAccount>();
        query.addWhereEqualTo("name", account.getName());
        query.findObjects(context, new FindListener<UserAccount>() {
            @Override
            public void onSuccess(List<UserAccount> list) {
                if (list.size() != 0) {
                    account.setObjectId(list.get(0).getObjectId());
                    updata(account);
                } else {
                    Toast.makeText(context, "用户名不存在！", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            @Override
            public void onError(int i, String s) {
                Toast.makeText(context, "更新失败：" + s.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void updata(UserAccount userAccount){
        userAccount.update(context, userAccount.getObjectId(), new UpdateListener() {
            @Override
            public void onSuccess() {
                Toast.makeText(context, "更新成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(context, "更新失败！", Toast.LENGTH_SHORT).show();
            }
        });
    }
    /**
     * 查询一条数据
     * 需要重写returnUser(UserAccount account)获取UserAccount对象数据
     * @param userName
     */
    public  void quertByName(String userName) {
        //查询用户名为userName

        BmobQuery<UserAccount> query = new BmobQuery<UserAccount>();
        query.addWhereEqualTo("name", userName);
        query.findObjects(context, new FindListener<UserAccount>() {
            @Override
            public void onSuccess(List<UserAccount> list) {
                if (list.size() != 0) {
                    returnUser(list.get(0));
                } else {
                    Toast.makeText(context, "数据不存在！", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            @Override
            public void onError(int i, String s) {
                Toast.makeText(context, "查询失败：" + s.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void returnUser(UserAccount account) {
    }
    /**
     * 查询所有数据
     * 需要重写returnUser(List<UserAccount> account)获取UserAccount对象集合数据
     *
     */
   public void queryAll(){
       BmobQuery<UserAccount> query = new BmobQuery<UserAccount>();
       query.findObjects(context, new FindListener<UserAccount>() {
           @Override
           public void onSuccess(List<UserAccount> list) {
               Toast.makeText(context, "查询成功！", Toast.LENGTH_SHORT).show();
               returnUser(list);
           }
           @Override
           public void onError(int i, String s) {
               Toast.makeText(context, "查询失败！" + s.toString(), Toast.LENGTH_SHORT).show();
           }
        });
    }
    public void returnUser(List<UserAccount> account) {
    }
    //----------------------------网络数据操作功能结束--------------------------------------//
    //----------------------------实时消息推送功能开始--------------------------------------//
    //更新用户与设备绑定信息
    public void updateBmobInstallation(final String name){
        BmobQuery<Installation> query = new BmobQuery<Installation>();
        query.addWhereEqualTo("installationId", BmobInstallation.getInstallationId(this));
        query.findObjects(context, new FindListener<Installation>() {
            @Override
            public void onSuccess(List<Installation> list) {
                if(list.size()>0){
                    Installation ins = list.get(0);
                    ins.setName(name);
                    if("a".equals(name)){
                        ins.setIsDeveloper(true);
                    }else {
                        ins.setIsDeveloper(false);
                    }
                    ins.update(context, new UpdateListener() {
                        @Override
                        public void onSuccess() {
                            Toast.makeText(context, "更新成功", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onFailure(int i, String s) {

                        }
                    });
                }
            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }

    //用户反馈
    public void sendMsg(final String from_name, final String to_name, final String msg){

        Feedback feedback = new Feedback();
        feedback.setFrom_name(from_name);
        feedback.setTo_name(to_name);
        feedback.setUser_content(msg);
        feedback.save(context, new SaveListener() {
            @Override
            public void onSuccess() {
                pushMsg(to_name, msg);
                Toast.makeText(context, "反馈成功！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(context, "反馈失败！"+s.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void pushMsg(String name,String msg){
        BmobQuery<BmobInstallation> query = BmobInstallation.getQuery();
        query.addWhereEqualTo("isDeveloper",true);
        query.addWhereNotEqualTo("name", name);
        bmobPush.setQuery(query);
        bmobPush.pushMessage(msg);
    }
    //给全员发送消息
    public void pushMsgAll(String msg){
        BmobQuery<BmobInstallation> query = BmobInstallation.getQuery();
        //bmobPush.setQuery(query);
        bmobPush.pushMessageAll(msg);
    }










    //----------------------------实时消息推送功能结束--------------------------------------//
    //----------------------------App推送功能开始--------------------------------------//


    //----------------------------App推送功能结束--------------------------------------//




}
